//出票模块实现
#include "../inc/ticket_print.h"
#include "../inc/movie_ticket.h" 
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // For atof

// 全局变量定义
Ticket g_user_tickets[MAX_PURCHASE_RECORDS];
int g_num_user_tickets = 0;

/**
 * @brief 加载指定用户的购票记录
 * @param username 要加载记录的用户名
 * @param tickets 存储购票记录的数组
 * @param max_tickets 数组的最大容量
 * @return 实际加载的记录数量，-1表示文件读取失败
 */
int load_purchase_records(const char *username, Ticket tickets[], int max_tickets) {
    FILE *file = fopen(PURCHASE_RECORDS_FILE_PATH, "r");
    if (file == NULL) {
        printf("购票记录文件 %s 不存在或无法打开。\n", PURCHASE_RECORDS_FILE_PATH);
        fflush(stdout);
        return 0; // 文件不存在，返回0条记录
    }

    char line[512]; // 假设一行最长512字符
    int count = 0;

    printf("正在从文件加载购票记录...\n");
    fflush(stdout);
    while (fgets(line, sizeof(line), file) != NULL && count < max_tickets) {
        char line_copy[512]; // 使用副本，因为 strtok_r 会修改字符串
        strncpy(line_copy, line, sizeof(line_copy) - 1);
        line_copy[sizeof(line_copy) - 1] = '\0';
        line_copy[strcspn(line_copy, "\n")] = 0; // 移除换行符

        char *token;
        char *rest = line_copy;

        // 解析票号
        token = strtok_r(rest, ",", &rest);
        if (token == NULL) continue;
        strncpy(tickets[count].ticket_id, token, sizeof(tickets[count].ticket_id) - 1);
        tickets[count].ticket_id[sizeof(tickets[count].ticket_id) - 1] = '\0';

        // 解析用户名
        token = strtok_r(rest, ",", &rest);
        if (token == NULL) continue;
        strncpy(tickets[count].username, token, sizeof(tickets[count].username) - 1);
        tickets[count].username[sizeof(tickets[count].username) - 1] = '\0';

        // 只有当前登录的用户才能查询自己的票
        if (strcmp(tickets[count].username, username) != 0) {
            continue; // 跳过不属于当前用户的记录
        }

        // 解析电影ID
        token = strtok_r(rest, ",", &rest);
        if (token == NULL) continue;
        strncpy(tickets[count].movie_id, token, sizeof(tickets[count].movie_id) - 1);
        tickets[count].movie_id[sizeof(tickets[count].movie_id) - 1] = '\0';

        // 解析场次ID
        token = strtok_r(rest, ",", &rest);
        if (token == NULL) continue;
        strncpy(tickets[count].session_id, token, sizeof(tickets[count].session_id) - 1);
        tickets[count].session_id[sizeof(tickets[count].session_id) - 1] = '\0';

        // 解析票数 (这里固定为1)
        token = strtok_r(rest, ",", &rest);
        if (token == NULL) continue;
        tickets[count].ticket_count = atoi(token);

        // 解析座位信息
        token = strtok_r(rest, ",", &rest);
        if (token == NULL) continue;
        strncpy(tickets[count].seat_info, token, sizeof(tickets[count].seat_info) - 1);
        tickets[count].seat_info[sizeof(tickets[count].seat_info) - 1] = '\0';

        // 解析票价
        token = strtok_r(rest, ",", &rest);
        if (token == NULL) continue;
        tickets[count].price = atof(token);

        // 解析购买时间戳
        token = strtok_r(rest, ",", &rest);
        if (token == NULL) continue;
        strncpy(tickets[count].purchase_time, token, sizeof(tickets[count].purchase_time) - 1);
        tickets[count].purchase_time[sizeof(tickets[count].purchase_time) - 1] = '\0';
        
        tickets[count].selected_for_print = false; // 默认未选中
        tickets[count].ui_panel = NULL; // 默认无UI对象关联

        count++;
    }

    fclose(file);
    printf("已为用户 '%s' 加载 %d 条购票记录。\n", username, count);
    fflush(stdout);
    return count;
}

/**
 * @brief 从购票记录文件中移除指定票号的记录
 * @param ticket_id_to_remove 要移除的票号
 * @return 0成功，-1失败
 */
int remove_purchase_record(const char *ticket_id_to_remove) {
    FILE *original_file = fopen(PURCHASE_RECORDS_FILE_PATH, "r");
    if (original_file == NULL) {
        printf("错误：无法打开购票记录文件 %s 进行读取。\n", PURCHASE_RECORDS_FILE_PATH);
        fflush(stdout);
        return -1;
    }

    FILE *temp_file = fopen("temp_purchase_records.txt", "w"); // 创建临时文件
    if (temp_file == NULL) {
        printf("错误：无法创建临时文件 temp_purchase_records.txt。\n");
        fflush(stdout);
        fclose(original_file);
        return -1;
    }

    char line[512];
    int removed_count = 0;

    printf("正在移除票号 '%s' 的记录...\n", ticket_id_to_remove);
    fflush(stdout);
    while (fgets(line, sizeof(line), original_file) != NULL) {
        char line_copy[512];
        strncpy(line_copy, line, sizeof(line_copy) - 1);
        line_copy[sizeof(line_copy) - 1] = '\0';

        char *token = strtok(line_copy, ",");
        if (token != NULL && strcmp(token, ticket_id_to_remove) == 0) {
            printf("已跳过要移除的记录：'%s'\n", line);
            fflush(stdout);
            removed_count++;
        } else {
            fprintf(temp_file, "%s", line); // 将未移除的记录写入临时文件
        }
    }

    fclose(original_file);
    fclose(temp_file);

    if (removed_count > 0) {
        if (remove(PURCHASE_RECORDS_FILE_PATH) != 0) {
            printf("错误：无法删除原购票记录文件 %s。\n", PURCHASE_RECORDS_FILE_PATH);
            fflush(stdout);
            return -1;
        }
        if (rename("temp_purchase_records.txt", PURCHASE_RECORDS_FILE_PATH) != 0) {
            printf("错误：无法重命名临时文件到 %s。\n", PURCHASE_RECORDS_FILE_PATH);
            fflush(stdout);
            return -1;
        }
        printf("成功移除 %d 条购票记录。\n", removed_count);
        fflush(stdout);
        return 0;
    } else {
        printf("未找到票号 '%s' 的记录，未进行移除。\n", ticket_id_to_remove);
        fflush(stdout);
        remove("temp_purchase_records.txt"); // 删除未使用的临时文件
        return -1;
    }
}
